<template>
  <div ref="chartDom" style="width: 100%; aspect-ratio: 10 / 7"></div>
</template>

<script lang="ts" setup>
import * as echarts from "echarts";
import { getUsersTypeCountApi } from "@/apis/admin";

const chartDom: any = ref();

let chartInstance: any = null;
let chartTestColor: string = "#808080";

let option = {
  title: {
    text: "平台用户类型统计图",
    subtext: "平台总用户数：0",
    left: "center",
    textStyle: {
      color: chartTestColor,
    },
  },
  tooltip: {
    trigger: "item",
  },
  legend: {
    top: "94%",
    left: "center",
    textStyle: {
      color: chartTestColor,
    },
  },
  series: [
    {
      name: "平台用户类型统计图",
      type: "pie",
      radius: ["40%", "70%"],
      avoidLabelOverlap: false,
      padAngle: 2,
      itemStyle: {
        borderRadius: 10,
      },
      label: {
        show: false,
        position: "center",
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: "bold",
        },
      },
      labelLine: {
        show: false,
      },
      data: [] as any,
    },
  ],
};

function initCharts() {
  if (!chartDom.value) return;

  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }

  chartInstance = echarts.init(chartDom.value);
  chartInstance.setOption(option);

  window.addEventListener("resize", function () {
    resizeChart();
  });
}

function resizeChart() {
  if (chartInstance) {
    chartInstance.resize();
  }
}

async function getUsersTypeCount() {
  try {
    const res: any = await getUsersTypeCountApi();
    if (res.code === 0) {
      option.title.subtext = "平台总用户数：" + res.data.allTypeCount;
      option.series[0].data = [
        {
          value: res.data.type0Count,
          name: "玩家",
          itemStyle: { color: "#409eff" },
          label: { color: "#409eff" },
        },
        {
          value: res.data.type1Count,
          name: "独立游戏作者",
          itemStyle: { color: "#9b59b6" },
          label: { color: "#9b59b6" },
        },
        {
          value: res.data.type2Count,
          name: "游戏开发商",
          itemStyle: { color: "#3375b9" },
          label: { color: "#3375b9" },
        },
        {
          value: res.data.type3Count,
          name: "平台管理员",
          itemStyle: { color: "#67c23a" },
          label: { color: "#67c23a" },
        },
        {
          value: res.data.otherTypeCount,
          name: "其他",
          itemStyle: { color: "#f56c6c" },
          label: { color: "#f56c6c" },
        },
      ];
      if (chartInstance) {
        chartInstance.setOption(option);
      }
    }
  } catch (error) {
  } finally {
  }
}

onMounted(async () => {
  await getUsersTypeCount();
  nextTick(() => {
    initCharts();
  });
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", resizeChart);
});
</script>
